/*
 * @Author: your name
 * @Date: 2021-03-09 11:41:41
 * @LastEditTime: 2021-04-01 11:42:08
 * @LastEditors: lily
 * @Description: In User Settings Edit
 * @FilePath: \testcodeg:\work\leetcode\code\628.三个数的最大乘积.js
 */
/*
 * @lc app=leetcode.cn id=628 lang=javascript
 *
 * [628] 三个数的最大乘积
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
 */

//  思路：
//  遍历一遍 求出数组中最大的三个数以及最小的两个数，比较乘积大小

//  复杂度：
//  O(n)  O(1)

var maximumProduct = function (nums) {
    var max1 = -Infinity, max2 = -Infinity, max3 = -Infinity
    var min1 = Infinity, min2 = Infinity
    for (var i = 0; i < nums.length; i++) {
        if (nums[i] < min1) {
            min2 = min1
            min1 = nums[i]
        } else if (nums[i] < min2) {
            min2 = nums[i]
        }
        if (nums[i] > max1) {
            max3 = max2
            max2 = max1
            max1 = nums[i]
        } else if (nums[i] > max2) {
            max3 = max2
            max2 = nums[i]
        } else if (nums[i] > max3) {
            max3 = nums[i]
        }
    }
    return Math.max(max1 * max2 * max3, max1 * min1 * min2)
};
// @lc code=end

